package cn.edu.xjtu.carlWay.backTrack.permutationsII;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 47. 全排列 II
 * 给定一个可包含重复数字的序列 nums ，按任意顺序 返回所有不重复的全排列。
 * <p>
 * https://leetcode-cn.com/problems/permutations-ii/
 */
public class Solution {
    public static void main(String[] args) {
        int[] nums = {0, 1, 0, 0, 9};
        Solution solution = new Solution();
        System.out.println(solution.permuteUnique(nums));
    }

    List<List<Integer>> result = new ArrayList<>();
    Deque<Integer> seq = new LinkedList<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        backtrack(nums, 0);
        return result;
    }

    private void backtrack(int[] nums, int index) {
        if (index == nums.length) {
            result.add(new ArrayList<>(seq));
        } else {
            int[] used = new int[21];
            for (int i = index; i < nums.length; i++) {
                if (used[nums[i] + 10] == 1) {
                    continue;
                }
                used[nums[i] + 10] = 1;
                swap(nums, index, i);
                seq.addLast(nums[index]);
                backtrack(nums, index + 1);
                swap(nums, index, i);
                seq.removeLast();
            }
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
